import 'dart:io';

import 'package:casdon/app/config/theme/theme_extention.dart';
import 'package:casdon/core/extentions/string_validation.dart';
import 'package:casdon/core/logger/log.dart';
import 'package:casdon/common/widget/fullscreen_loading_overlay.dart';
import 'package:casdon/modules/device/application/notification/product_category_notifier.dart';
import 'package:casdon/modules/device/data/model/product_category_model.dart';
import 'package:casdon/auto_router.dart';
import 'package:flutter/material.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';

/// 选中索引 Provider
final selectedIndexProvider = StateProvider<int>((ref) => 0);

class ProductCategoryWidget extends HookConsumerWidget {
  const ProductCategoryWidget({super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    // 1. 获取状态管理相关对象
    final productCategoryNotifier = ref.watch(
      productCategoryNotifierProvider.notifier,
    );
    final productState = ref.watch(productCategoryNotifierProvider);

    // 2. 使用StateProvider管理选中索引
    final selectedIndex = ref.watch(selectedIndexProvider);

    // 1. 创建初始化标记
    final isInitialized = useRef(false);
    // 2. 定义数据加载方法（无依赖项）
    final fetchData = useCallback(() async {
      try {
        final newState = await productCategoryNotifier.fetchData();
        if (newState.data.isNotEmpty) {
          ref.read(selectedIndexProvider.notifier).state = 0;
          await productCategoryNotifier.fetchProductModel(0);
        }
      } catch (error) {
        Log.e("加载数据失败", error, StackTrace.current);
      }
    }, []); // 注意：这里移除所有依赖

    // 3. 执行初始化（仅首次）
    useEffect(() {
      if (!isInitialized.value) {
        isInitialized.value = true;
        Future.microtask(fetchData);
      }
      return null;
    }, []); // 空依赖确保只运行一次

    return Row(
      children: [
        // 左侧类目列表
        SizedBox(
          width: 90.w,
          child: ListView.builder(
            itemCount: productState.data.length,
            itemBuilder: (context, index) {
              final isSelected = index == selectedIndex;
              return GestureDetector(
                onTap: () {
                  ref.read(selectedIndexProvider.notifier).state = index;
                  Future.microtask(() {
                    productCategoryNotifier.fetchProductModel(index);
                  });
                },
                child: Container(
                  color: isSelected
                      ? Colors.white
                      : context.customColorThemeNonNull.bgColorF7,
                  padding: EdgeInsets.symmetric(vertical: 14.h),

                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      // 蓝色竖条（靠左）
                      Align(
                        alignment: Alignment.centerLeft,
                        child: ColoredBox(
                          color: isSelected
                              ? context.colorScheme.primary
                              : Colors.transparent,
                          child: SizedBox(height: 14.h, width: 3.w),
                        ),
                      ),
                      // 文本内容（居中）
                      Expanded(
                        // 关键修改：让Text占据剩余空间
                        child: Center(
                          child: Text(
                            productState.data[index].name,
                            style: TextStyle(
                              fontSize: 14.r,
                              color: isSelected
                                  ? context.colorScheme.primary
                                  : context.customColorThemeNonNull.textColor3,
                              fontWeight: isSelected
                                  ? FontWeight.w600
                                  : FontWeight.normal,
                            ),
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              );
            },
          ),
        ),

        // 右侧网格 + 遮罩
        Expanded(
          child: ColoredBox(
            color: Colors.white,
            child: FullscreenLoadingOverlay(
              backgroundColor: Colors.transparent,
              loading: productState.isLoading,
              child: GridView.builder(
                padding: EdgeInsets.zero,
                itemCount: selectedIndex < productState.data.length
                    ? productState.data[selectedIndex].modelList.length
                    : 0,
                gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: 3,
                  crossAxisSpacing: 0.w,
                  mainAxisSpacing: 0.h,
                  childAspectRatio: 0.85715,
                ),
                itemBuilder: (context, index) {
                  final item =
                      productState.data[selectedIndex].modelList[index];
                  return GestureDetector(
                    onTap: () {
                      _goPairNetGuid(item, context);
                    },
                    child: Padding(
                      padding: EdgeInsets.symmetric(horizontal: 8.w),
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Container(
                            height: 45.w,
                            width: 45.w,
                            alignment: Alignment.center,
                            child: CachedNetworkImage(
                              imageUrl: item.icoUrl.isUrl()
                                  ? item.icoUrl
                                  : "https://i.ibb.co/j9K4KJ6K/541-3x.png",
                              placeholder: (_, __) =>
                                  Container(color: Colors.grey[200]),
                              errorWidget: (_, __, ___) =>
                                  const Icon(Icons.broken_image),
                              fit: BoxFit.contain,
                            ),
                          ),
                          SizedBox(height: 12.h),
                          Text(
                            item.name,
                            textAlign: TextAlign.center,
                            maxLines: 2,
                            overflow: TextOverflow.ellipsis,
                            style: TextStyle(fontSize: 12.r),
                          ),
                        ],
                      ),
                    ),
                  );
                },
              ),
            ),
          ),
        ),
      ],
    );
  }

  void _goPairNetGuid(ProductModelModel model, BuildContext context) async {
    //只做页面导航
    if (model.source == ProductSource.tuya) {
      TuyaPairnetGuidRoute(pid: model.id, deviceName: model.name).push(context);
    } else {
      TuyaPairnetGuidRoute(pid: model.id, deviceName: model.name).push(context);
    }
  }
}
